package logic_settings_user

import (
	v1 "Sailor/app/Sailor-console-server/api/api_task/v1"
	"Sailor/app/Sailor-console-server/internal/consts"
	"Sailor/app/Sailor-console-server/internal/dao"
	"Sailor/app/Sailor-console-server/internal/model/do"
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"Sailor/app/Sailor-console-server/utility/utility_task"
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/google/uuid"
)

func (s *sTask) LogicTaskCreate(ctx context.Context, req *v1.TaskCreateReq) (res *v1.TaskCreateRes, err error) {
	uid := uuid.New().String()

	_, err = dao.SysTask.Ctx(ctx).Insert(&do.SysTask{
		Uuid:              uid,
		TaskName:          req.TaskName,
		TaskGroup:         req.TaskGroup,
		TaskCron:          req.TaskCron,
		TaskInvokeTarget:  req.TaskInvokeTarget,
		TaskArgs:          req.TaskArgs,
		TaskHttpMethod:    req.TaskHttpMethod,
		TaskTimeout:       req.TaskTimeout,
		TaskMulti:         req.TaskMulti,
		TaskRetryTimes:    req.TaskRetryTimes,
		TaskRetryInterval: req.TaskRetryInterval,
		TaskTag:           req.TaskTag,
		TaskRemark:        req.TaskRemark,
		TaskStatus:        req.TaskStatus,
	})
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("创建失败")
	}

	if req.TaskStatus == consts.Enabled {
		err := utility_task.Add(context.Background(), entity.SysTask{
			Uuid:              uid,
			TaskName:          req.TaskName,
			TaskGroup:         req.TaskGroup,
			TaskCron:          req.TaskCron,
			TaskInvokeTarget:  req.TaskInvokeTarget,
			TaskArgs:          req.TaskArgs,
			TaskHttpMethod:    req.TaskHttpMethod,
			TaskTimeout:       req.TaskTimeout,
			TaskMulti:         req.TaskMulti,
			TaskRetryTimes:    req.TaskRetryTimes,
			TaskRetryInterval: req.TaskRetryInterval,
			TaskTag:           req.TaskTag,
			TaskRemark:        req.TaskRemark,
			TaskStatus:        req.TaskStatus,
		})
		if err != nil {
			g.Log().Error(ctx, err)
			return nil, gerror.New("添加到任务队列失败")
		}
	}

	return &v1.TaskCreateRes{Uuid: uid}, nil
}
